package com.xf.system.utils.ip;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * IP工具类
 * @author xiefengf
 */
public class IpUtils {

    private static final Logger log = LoggerFactory.getLogger(IpUtils.class);

    public static final String USER_AGENT = "User-Agent";

    /**
     * 太平洋网络IP地址查询Web接口（适用国内外城市）
     */
    private static final String WHOIS_IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    /**
     * 淘宝（适用国内外城市） --- 每个用户的访问频率需小于1qps
     */
    private static final String TAO_BAO_IP_URL = "https://ip.taobao.com/outGetIpInfo";

    /**
     * 未知地址
     */
    private static final String UNKNOWN = "未知地址";
    /**
     * 超时时间
     */
    private static final Integer TIMEOUT = 3000;

    /**
     * 根据IP获取真实的地理位置信息  --- <a href="https://blog.csdn.net/weixin_44825912/article/details/129715526">...</a>
     * @param ip
     * @return
     */
    public static String getRealAddressByIp(String ip,Integer count){
        try {
            // 内网不查询
            if (internalIp(ip)) {
                return "内网IP";
            }
            String address = UNKNOWN;
            try {
                if (count <= 3){
                    address = getRealAddressByTaoBaoIp(ip);
                }
            } catch (Exception e) {
                // 最多重试2次。总共最多调用3次（递归）
                Thread.sleep(1000);
                count++;
                address = getRealAddressByIp(ip,count);
            }
            return address;
        } catch (Exception e) {
            log.error("获取地理位置异常 {},错误信息 {}", ip,e);
        }
        return UNKNOWN;
    }

    /**
     * 太平洋网络IP地址查询Web接口
     * @param ip
     * @return
     */
    public static String getRealAddressByWhoisIp(String ip) {
        try {
            HashMap<String,Object> requestMap = new HashMap<>();
            requestMap.put("ip",ip);
            requestMap.put("json","true");
            String body = HttpRequest.get(WHOIS_IP_URL)
                    .form(requestMap)
                    .timeout(TIMEOUT)
                    .cookie("")
                    .execute().body();
            JSONObject obj = JSONUtil.parseObj(body);
            String region = obj.getStr("pro");
            String city = obj.getStr("city");
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            throw new RuntimeException("太平洋网络IP地址查询Web接口获取真实地址失败");
        }
    }

    /**
     * 淘宝IP地址接口
     * @param ip
     * @return
     */
    public static String getRealAddressByTaoBaoIp(String ip) {
        try {
            HashMap<String,Object> requestMap = new HashMap<>();
            requestMap.put("ip",ip);
            requestMap.put("accessKey","alibaba-inc");
            String body = HttpRequest.get(TAO_BAO_IP_URL)
                    .form(requestMap)
                    .timeout(TIMEOUT)
                    .cookie("")
                    .execute().body();
            JSONObject obj = JSONUtil.parseObj(body);
            Integer code = obj.getInt("code");
            if (code != 0){
                throw new RuntimeException("每个用户的访问频率需小于1qps");
            }
            Object data = obj.get("data");
            JSONObject object = JSONUtil.parseObj(data);
            String country = object.getStr("country");
            String region = object.getStr("region");
            String city = object.getStr("city");
            return String.format("%s %s %s",country,region, city);
        } catch (Exception e) {
            throw new RuntimeException("淘宝IP地址查询Web接口获取真实地址失败");
        }
    }

    /**
     * 获取客户端IP --- 方式一
     *
     * @param request 请求对象
     * @return IP地址
     */
    public static String getIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        // 如果使用代理，可能会有多个IP地址，其中第一个IP地址是客户端的真实IP
        if (ipAddress != null && ipAddress.contains(",")) {
            ipAddress = ipAddress.split(",")[0].trim();
        }
        return ipAddress;
    }

    /**
     * 检查是否为内部IP地址
     *
     * @param ip IP地址
     * @return 结果
     */
    public static boolean internalIp(String ip) {
        byte[] addr = textToNumericFormatV4(ip);
        return internalIp(addr) || "127.0.0.1".equals(ip);
    }

    /**
     * 检查是否为内部IP地址
     *
     * @param addr byte地址
     * @return 结果
     */
    private static boolean internalIp(byte[] addr) {
        if (addr == null || addr.length < 2) {
            return true;
        }
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        // 10.x.x.x/8
        final byte SECTION_1 = 0x0A;
        // 172.16.x.x/12
        final byte SECTION_2 = (byte) 0xAC;
        final byte SECTION_3 = (byte) 0x10;
        final byte SECTION_4 = (byte) 0x1F;
        // 192.168.x.x/16
        final byte SECTION_5 = (byte) 0xC0;
        final byte SECTION_6 = (byte) 0xA8;
        switch (b0) {
            case SECTION_1:
                return true;
            case SECTION_2:
                if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                    return true;
                }
            case SECTION_5:
                switch (b1) {
                    case SECTION_6:
                        return true;
                }
            default:
                return false;
        }
    }

    /**
     * 将IPv4地址转换成字节
     *
     * @param text IPv4地址
     * @return byte 字节
     */
    public static byte[] textToNumericFormatV4(String text) {
        if (text.length() == 0) {
            return null;
        }
        byte[] bytes = new byte[4];
        String[] elements = text.split("\\.", -1);
        try {
            long l;
            int i;
            switch (elements.length) {
                case 1:
                    l = Long.parseLong(elements[0]);
                    if ((l < 0L) || (l > 4294967295L)) {
                        return null;
                    }
                    bytes[0] = (byte) (int) (l >> 24 & 0xFF);
                    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 2:
                    l = Integer.parseInt(elements[0]);
                    if ((l < 0L) || (l > 255L)) {
                        return null;
                    }
                    bytes[0] = (byte) (int) (l & 0xFF);
                    l = Integer.parseInt(elements[1]);
                    if ((l < 0L) || (l > 16777215L)) {
                        return null;
                    }
                    bytes[1] = (byte) (int) (l >> 16 & 0xFF);
                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 3:
                    for (i = 0; i < 2; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    l = Integer.parseInt(elements[2]);
                    if ((l < 0L) || (l > 65535L)) {
                        return null;
                    }
                    bytes[2] = (byte) (int) (l >> 8 & 0xFF);
                    bytes[3] = (byte) (int) (l & 0xFF);
                    break;
                case 4:
                    for (i = 0; i < 4; ++i) {
                        l = Integer.parseInt(elements[i]);
                        if ((l < 0L) || (l > 255L)) {
                            return null;
                        }
                        bytes[i] = (byte) (int) (l & 0xFF);
                    }
                    break;
                default:
                    return null;
            }
        } catch (NumberFormatException e) {
            return null;
        }
        return bytes;
    }

}